﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.IO;
using System.Drawing.Drawing2D;
using System.Data.SqlClient;
using System.Data;
using System.Threading;
using System.Drawing.Imaging;
using MySql.Data.MySqlClient;

//using HtmlAgilityPack;

namespace AsianSocietyPictureUpload
{
    partial class AsianSocietyUploadPicturesToDatabase
    {
        private string fileName;
        private string file;
        private string urlGlobal;
        private string url;
        private AsiaDB.tb_city_infoDataTable dtCoord;
        private AsiaDB.tb_city_infoDataTable dtSataInfo;
        private AsianSocietyPictureUpload.Properties.Settings setString = new Properties.Settings();
 
        //private DataTable dtCityTime;
        private Thread m_St;
        private Thread m_StRaw;
        private Thread m_pD;
        private DateTime dateInsert;
        private string satellitePath;
        private string groundPath;
        private string rawsatellitePath;
        private string rawgroundPath;
        private string sponserPath;
        private string cityMapPath;
        private string newuploadPath;

 
          
        public AsianSocietyUploadPicturesToDatabase()
        {
            try
            {
                foreach (System.Diagnostics.Process myProc in System.Diagnostics.Process.GetProcesses())
                {
                    DateTime currentTime = new DateTime();
                    currentTime = DateTime.Now.Subtract(new TimeSpan(0, 0, 5));
                    if (myProc.ProcessName == "AsianSocietyPictureUpload" && myProc.StartTime < currentTime)
                        myProc.Kill();
                }


                GetCoordinates();
                GetCoordinates2();
                // SetCityUrl();
                SetPaths();
                // GetCityTime();
            }
            catch (Exception e)
            {
                System.Windows.Forms.MessageBox.Show(e.Message);
            }

            m_pD = new Thread(new ThreadStart(UploadPollutionData));
            m_St = new Thread(new ThreadStart(UploadImageProcess));
            m_StRaw = new Thread(new ThreadStart(FixRawFiles));

            //UploadPollutionData();

          //  UploadImageProcess();

         //   FixRawFiles();

            m_pD.Start();
            m_St.Start();
            m_StRaw.Start();
        }


        private void UploadPollutionData()
        {
            while (m_pD.IsAlive)
           {
                GetPollutionData();

                Thread.Sleep(1700000); //1 Hour
           }
            
        }


        //private void GetCityTime()
        //{
        //    AsiaDBTableAdapters.tb_city_infoTableAdapter cityInfoAd = new AsiaDBTableAdapters.tb_city_infoTableAdapter();


        //    SqlConnection myConnection = new SqlConnection();
        //    myConnection.ConnectionString = "Data Source=HIPPO;Initial Catalog=AsiaSociety;Integrated Security=True";
        //    myConnection.Open();

        //    string SQL = "SELECT * FROM [AsiaSociety].[dbo].[City];";

        //    SqlDataAdapter adaptor = new SqlDataAdapter(SQL, myConnection);

        //    dtCityTime = new DataTable();
        //    adaptor.Fill(dtCityTime);

        //    myConnection.Close();
        //}

        //private void SetCityUrl()
        //{
        //    SqlConnection myConnection = new SqlConnection();
        //    myConnection.ConnectionString = "Data Source=HIPPO;Initial Catalog=AsiaSociety;Integrated Security=True";
        //    myConnection.Open();

        //    string SQL = "SELECT d.CityName ,a.[Path], c.[Value] FROM [AsiaSociety].[dbo].[CityPicture] a, [AsiaSociety].[dbo].[UploadMethod] b, [AsiaSociety].[dbo].[PictureExtention] c, [AsiaSociety].[dbo].[City] d Where b.UploadMethodID = 1000 AND a.PictureExtentionID = c.PictureExtentionID AND a.CityID = d.CityID ;";

        //    SqlDataAdapter adaptor = new SqlDataAdapter(SQL, myConnection);

        //    dtCoord = new DataTable();
        //    adaptor.Fill(dtCoord);

        //    myConnection.Close();
        //} 

        private void SetPaths()
        {
            AsiaDBTableAdapters.tb_globalTableAdapter globalAd = new AsiaDBTableAdapters.tb_globalTableAdapter();
            urlGlobal = globalAd.GetNASAURL();
            satellitePath = globalAd.GetSateImagePath();
            groundPath = globalAd.GetGroundImagePath();
            rawgroundPath = globalAd.GetRawGroundImagePath();
            rawsatellitePath = globalAd.GetRawSatImagePath();
            cityMapPath = globalAd.GetCityMap();
            sponserPath = globalAd.GetSponser();
            newuploadPath = globalAd.GetNewUpload().ToString(); ;

            if (!Directory.Exists(satellitePath))
                Directory.CreateDirectory(satellitePath);
            if (!Directory.Exists(groundPath))
                Directory.CreateDirectory(groundPath);

            if (!Directory.Exists(rawgroundPath))
                Directory.CreateDirectory(rawgroundPath);
            if (!Directory.Exists(rawsatellitePath))
                Directory.CreateDirectory(rawsatellitePath);


            if (!Directory.Exists(cityMapPath))
                Directory.CreateDirectory(cityMapPath);
            if (!Directory.Exists(sponserPath))
                Directory.CreateDirectory(sponserPath);

            if (!Directory.Exists(newuploadPath))
                Directory.CreateDirectory(newuploadPath);
        }

        public void UploadImageProcess()
        {
           while (m_St.IsAlive)
            {
                UpdateSatelliteImages();

                Thread.Sleep(3400000); //1 Hours
           }
        }

        private void FixRawFiles()
        {
           while (m_StRaw.IsAlive)
            {
              // FixRawGround();      //Tranform and Transform of Raw Ground Pictures
              //  FixRawSatellite();   //Tranform and Transform of Raw Satellite Pictures
                CheckNewUpload();
                Thread.Sleep(3000); //3 Seconds
           }
        }

        private string GetCityName(string City)
        {
            switch (City)
            {
                case "CCNY":
                    return "New York";
                case "Hangzhou":
                    return "Shanghai";
                case "HKPolyU":
                    return "Hong Kong";
                case "UCSB":
                    return "Los Angeles";
                case "La_Jolla":
                    return "Los Angeles";
                case "BONDVILLE":
                    return "Chicago";
                default:
                    return City;
            }
        }

        private void GetCoordinates()
        {
            AsiaDBTableAdapters.tb_city_infoTableAdapter cityInfoAdapter = new AsiaDBTableAdapters.tb_city_infoTableAdapter();

            dtCoord = new AsiaDB.tb_city_infoDataTable();
            cityInfoAdapter.Fill(dtCoord);
        }

        private void GetCoordinates2()
        {
            try
            {
                AsiaDBTableAdapters.tb_city_infoTableAdapter cityInfoAdapter = new AsiaDBTableAdapters.tb_city_infoTableAdapter();
                dtSataInfo = null;
                dtSataInfo = new AsiaDB.tb_city_infoDataTable();
                cityInfoAdapter.Fill(dtSataInfo);
            }
            catch (Exception e)
            { }
        }

        private Image ResizeImage(Image image)
        {

            int destWidth = (int)(980);
            int destHeight = (int)(632);

            Bitmap b = new Bitmap(destWidth, destHeight);
            Graphics g = Graphics.FromImage((Image)b);
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;

            g.DrawImage(image, 0, 0, destWidth, destHeight);
            g.Dispose();

            b.SetResolution(72.0F, 72.0F);

            image.Dispose();

            return (Image)b;
        }

        private ImageCodecInfo GetEncoder(ImageFormat format)
        {

            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();

            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.FormatID == format.Guid)
                {
                    return codec;
                }
            }
            return null;
        }

        public void CloseApp()
        {
            m_St.Interrupt();
            m_St.Abort();

            foreach (System.Diagnostics.Process myProc in System.Diagnostics.Process.GetProcesses())
            {
                if (myProc.ProcessName == "AsianSocietyPictureUpload")
                    myProc.Kill();
            }

        }
    }
}
